$(document).ready(function() {
	$('.jquery_date_picker').datetime({
		userLang : 'en',
		dateFormat : DATE_FORMAT_DATETIMEPICKER_DISPLAY,
		hasTime : true,
		americanMode : false,
		showSecond : true,
		showMillisec : false,
		timeFormat : 'h:m:s',
	});
	$('.jquery_datetime_picker').datetime({
		userLang : 'en',
		dateFormat : DATE_FORMAT_DATETIMEPICKER_DISPLAY,
		hasTime : true,
		americanMode : false,
		showSecond : true,
		showMillisec : false,
		timeFormat : 'h:m:s',
	});
	$.validator.addMethod("maxTo", function(value, element,	params) {
		if ($.isArray(params)) {
			return false;
		}
		if($(params).length > 0) {
			var value2 = $(params).val();
			if ($.isNumeric(value) && $.isNumeric(value2)) {
				return parseFloat(value2) >= parseFloat(value);
			}
			//return new Date(value2) >= value.toDate();
			return value2.toDate() >= value.toDate();
		}
		return true;
	});
	$.validator.addMethod("datetime", function(value, element) {
		var date = (value+'').toDate();
		if(date == null) {
			date = value;
		}
		return $.validator.methods['date'].call(this,date,element);
		}  
	);
	$.validator.addMethod("atLeastCheck", function(value, element) {
		var list = $('#frmEditBet [name^="betInfo.betPosInfoList["][name$="].active"]');
		var isChecked = false;
		if (list != null) {
			for ( var i = 0; i < list.length; i++) {
				if (list[i].checked == true) {
					isChecked = true;
				}
			}
		}
		return isChecked;
	});
	$("#frmEditBet").validate({
		rules: {
		},
		messages: {
		}
	});
	$('#imgEvent').click(function(){
		if($('#_eventId').val() != null && $('#_eventId').val() != '') {
			$('#uploadImage').click();
		}
	});
	$('#uploadImage').change(function(){
		var options = {
			beforeSubmit : function(formData, jqForm, options) { // pre-submit
																	// callback
				var queryString = $.param(formData);
				if (queryString == '' || queryString == 'resourceFile=') {
					return false;
				}
				return true;
			},
			success : function(responseText, statusText) {
				_uploadSuccess(responseText, statusText);
			},
			error : function(xhr, ajaxOptions, thrownError) {
				alert(xhr.status);
				alert(thrownError);
			},
			url : UPLOAD_FILE_URL,
			type : 'post', // 'get' or 'post', override for form's 'method'
							// attribute
			dataType : 'json', // 'xml', 'script', or 'json' (expected server
								// response type)
			iframe : true
		};
		$('#frmUploadResource').ajaxSubmit(options);
	});
	
	$('#frmEditBet [name="betInfo.name"]').rules("add", {
		required : true,
		maxlength : 255,
		messages : {
			required : message_bet_name_required,
			maxlength : message_bet_name_maxlength
		}
	});
	$('#frmEditBet [name="betInfo.description"]').rules("add", {
		maxlength : 256,
		messages : {
			maxlength : message_bet_description_maxlength
		}
	});
	if($('#frmEditBet [name="betInfo.amount"]').length > 0) {
		$('#frmEditBet [name="betInfo.amount"]').rules("add", {
			required : true,
			number : true,
			maxlength : 15,
			min : 0,
			messages : {
				required : message_bet_housestake_required,
				number : message_bet_housestake_number,
				maxlength : message_bet_housestake_maxlength,
				min : message_bet_housestake_min
			}
		});
	}
	$('#frmEditBet [name="betInfo.minStake"]').rules("add", {
		required : true,
		number : true,
		maxlength : 15,
		maxTo : '#txtBetHouseStake',
		min : 0,
		messages : {
			required : message_bet_minstake_required,
			number : message_bet_minstake_number,
			maxlength : message_bet_minstake_maxlength,
			maxTo : message_bet_minstake_maxto,
			min : message_bet_minstake_min
		}
	});
	$('#frmEditBet [name="betInfo.stopDate"]').rules("add", {
		required : true,
		datetime : true,
		maxTo : '#hidEventEndDate',
		messages : {
			required : message_bet_stopdate_required,
			datetime : message_bet_stopdate_datetime,
			maxTo : message_bet_stopdate_maxto
		}
	});
	
	$('[id^="_oddvalue_"]').each(function() {
		var betPosId = $(this).attr('id').replace("_oddvalue_", "");
		calculateOddValue(betPosId);
	});
	
	validatePossibilities();
	
	applyComment(BET, $('#_betId').val());
	loadComment();
	applyInvite($('#_betId').val());
	loadInvite();
});

function validatePossibilities() {
	$('#frmEditBet [name^="betInfo.betPosInfoList["][name$="].active"]').each(function() {
		$(this).rules("add", {
			atLeastCheck : true,
			messages : {
				atLeastCheck : message_bet_betpos_required
			}
		});
	});
}

function validateOddValue(target) {
	var name = $(target).attr('name');
	var oddName = name.replace('active', 'oddValue');
	if ($(target).is(':checked')) {
		$('#frmEditBet [name="' + oddName + '"]').rules("add", {
			required : true,
			number : true,
			maxlength : 15,
			min : 1.01,
			messages : {
				required : message_bet_betpos_odd_required,
				number : message_bet_betpos_odd_number,
				maxlength : message_bet_betpos_odd_maxlength,
				min : message_bet_betpos_odd_min
			}
		});
	} else {
		$('#frmEditBet [name="' + oddName + '"]').rules("remove");
	}
}

function showJoinedBet(id) {
	$('#' + id).toggle();
}
function doEdit() {
	$('#tblViewBet').hide();
	$('#tblEditBet').show();
}
function doCancel() {
	$('#tblViewBet').show();
	$('#tblEditBet').hide();
}
function doSubmit() {
	//validateInfo();
	$('#frmEditBet').submit();
}

function doLoadParticipant(betId, possibilityId, parent, relation) {
	if($('#' + parent).is(":visible") == true) {
		$('#' + parent).hide();
		return;
	}
	$.ajax({
		url : LISTPARTICIPANT_AJAX_URL,
		dataType : 'json',
		type: 'post',
		iframe : true,
		data : {'betId' : betId, 'possibilityId' : possibilityId},
		success : function(data) {
			if(data.errorFlag == 0) {
				loadParticipantComplete(data, parent, relation);
			}
		},
		error : function(xhr, ajaxOptions, thrownError) {
			//alert(xhr.status);
			//alert(thrownError);
		}
	});
}

function loadParticipantComplete(data, parent, relation) {
	if(data.custBetPosInfoList == null || data.custBetPosInfoList.length <= 0) {
		return;
	}
	var custBetPosInfoList = data.custBetPosInfoList;
	var html = ''
		+ '<tr>'
		+ '  <td width="5">&nbsp;</td>'
		+ '  <td colspan="5" class="bottombordergray">Participants</td>'
		+ '</tr>';
	for(var i = 0; i < custBetPosInfoList.length; i++) {
		var custBetPosInfo = custBetPosInfoList[i];
		if(custBetPosInfo == null || custBetPosInfo.customerInfo == null) {
			continue;
		}
		var customerInfo = custBetPosInfo.customerInfo;
		var imagePath = getImage(customerInfo.displayImage);
		
		html = html + ""
			+ '<tr>'
            + '  <td align="right">&nbsp;</td>'
            + '  <td width="40" align="right"><img src="'+ imagePath + '" alt="' + NO_PICTURE_ALT + '" width="30" height="30" /></td>'
            + '  <td colspan="3"><a href="' + LIST_RECENTBET_URL + '?betInfo.customerId=' + customerInfo.customerId + '">' + customerInfo.displayName + '</a></td>'
            + '  <td class="alignright">$' + custBetPosInfo.stake + '</td>'
            + '</tr>';
	}
	$('[id^='+relation+']').hide();
	$('#' + parent).html(html);
	$('#' + parent).show();
}

function loadBetInfo(){
	$.ajax({
		url : LOADBET_AJAX_URL,
		data : {'betInfo.betId' : $('#_betId').val()},
		success : function(data) {
			$('#_betview').html(data);
		}
	});
}

function applyInvite(betId, _loadInvite, _containHeader) {
	var html = ''
			+ '<table width="100%" border="0" cellpadding="0" cellspacing="0">';
	if(_containHeader == true) {
		html = html + ''
				+ '<thead>'
				+ '  <tr>'
				+ '    <td class="bottomborder"><strong>INVITES</strong></td>';
        		+ '  </tr>'
        		+ '</thead>';
	}
	html = html + ''
			+ '<input type="hidden" value="' + betId + '" id="_invite_betId"/>'
			+ '  <tr>'
		    + '    <td width="100%" class="alignleft"><table bgcolor="#E4EAF6" width="100%" border="0" cellpadding="2" cellspacing="0" >'
			+ '      <tbody class="tborder" bgcolor="#E4EAF6" id="_tblInvite"></tbody>'
			+ '      <tfoot class="tborder" bgcolor="#E4EAF6" id="_tblInviteMore"></tfoot>'
			+ '    </table></td>'
			+ '  </tr>'
			+ '</table>';
	$('.invite_component').html(html);
	if(_loadInvite == true) {
		loadInvite();
	}
}

function loadInvite(betId, append, indexPage) {
	if(betId == null || betId == undefined || betId == '') {
		betId = $('#_invite_betId').val();
	}
	$.ajax({
		url : LOADINVITE_AJAX_URL,
		type: 'POST',
		data: {'betId': betId, 
			'pagingInfo.indexPage': append?indexPage:0},
		dataType : 'json',
		iframe : true,
		success : function(data) {
			loadInviteSuccess(data, append);
		}
	});
}

function loadInviteSuccess(data, append) {
	var inviteList = data.inviteList;
	if(inviteList != null && inviteList.length > 0) {
		var s = "";
		for(var i = 0; i < inviteList.length; i++) {
			var notificationInfo = inviteList[i];
			if(notificationInfo.toCustomer == null) {
				continue;
			}
			var imagePath = getImage(notificationInfo.toCustomer.displayImage);
			var customerName = notificationInfo.toCustomer.displayName;
			var inputDate = " ";
			if(notificationInfo.inputDate != null) {
				inputDate = notificationInfo.inputDateStr;
			}
			s = s + '<tr class="tr">'
			      + '  <td width="100%" class="topbordergray"><table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#E4EAF6" class="closeuicontainer">'
			      + '    <tr>'
			      + '      <td width="40" class="alignleft valigntop" rowspan="2"><img src="' + imagePath + '" alt="' + NO_PICTURE_ALT + '" width="30" height="30" /></td>'
			      + '      <td><strong><a href="' + BET_LIST_RECENTBET_URL + '?betInfo.customerId=' + notificationInfo.toCustomer.customerId + '">' + customerName + '</a></strong></td>'
			      + '    </tr>'
			      + '    <tr>  '
			      + '      <td class="alignleft">' + inputDate + '</td>'
			      + '    </tr>'
			      + '  </table></td>'
			      + '</tr>';
		}
		var pagingInfo = data.pagingInfo;
		if(pagingInfo && pagingInfo.hasNextPage == true) {
			$('#_tblInviteMore').html('' 
					+ '<tr>'
					+ '  <td width="100%" class="topbordergray alignleft"><table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#E4EAF6">'
					+ '    <tr>'
					+ '      <td></td>'
					+ '      <td width="5"></td>'
					+ '      <td class="alignleft"><a href="javascript: loadInvite(null, true, ' + (pagingInfo.indexPage + 1) +');">View all ' + pagingInfo.remainingItems + ' invites</a></td>'
					+ '    </tr>'
					+ '  </table></td>'
					+ '</tr>');
		} else {
			$('#_tblInviteMore').html('');
		}
		if(append) {
			$('#_tblInvite').append(s);
		} else {
			$('#_tblInvite').html(s);
		}
	}
}

function calculateOddValue(betPosId) {
	var defaultOddValue = $('#_oddvalue_' + betPosId).val();
	var stake = Number($('#frmJoinBet_stake_' + betPosId).val());
	if(stake != null && stake == 0) {
		$('#oddValue_' + betPosId).html(defaultOddValue);
		return;
	}
	var possibilityPotTotal = Number($('#_pot_total_' + betPosId).val()) + stake;
	var potTotal = Number($('#_potTotal').val()) + stake;
	var oddValue = (potTotal / possibilityPotTotal).round(2, -1);	
	if(oddValue != null) {
		$('#oddValue_' + betPosId).html(oddValue.toFixed(2));
	} else {
		$('#oddValue_' + betPosId).html(defaultOddValue);
	}
}

var color = "white";
function __swap(obj){
	color = obj.style.backgroundColor;
	obj.style.backgroundColor = '#eeeeee';
}
function __reSwap(obj){
	obj.style.backgroundColor = color;
}
function scrollbar(){
	var scrollBorderColor	=	"#7F8E91";
	var scrollFaceColor		=	"#F0F6FF";
	with (document.body.style) {
		scrollbarDarkShadowColor	=	scrollBorderColor;
		scrollbar3dLightColor		=	scrollBorderColor;
		scrollbarArrowColor			=	"black";
		scrollbarBaseColor			=	scrollFaceColor;
		scrollbarFaceColor			=	scrollFaceColor;
		scrollbarHighlightColor		=	scrollFaceColor;
		scrollbarShadowColor		=	scrollFaceColor;
		scrollbarTrackColor			=	"white";
	}			
}
function swapborder(obj) {
	obj.style.border = "0.2cm groove pink";
}
function reSwapborder(obj) {
	obj.style.border = "red";
}
function swap(obj) {
	obj.style.background = "#C9E9FC";
}
function reSwap(obj) {
	obj.style.background = "white";
}
function onFocus(inp) {
   defVal = inp.defaultValue;
   if (inp.value == defVal) { inp.value = '' };
}
function onBlur(inp2) {
   defVal = inp2.defaultValue;
   if (inp2.value == '') { inp2.value = defVal; }
}
